package moni.anyou.com.view.amap;

import android.util.Log;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import moni.anyou.com.view.R;
import moni.anyou.com.view.bean.InitTripDataBean;
import moni.anyou.com.view.bean.StartLocationBean;
import moni.anyou.com.view.config.SysConfig;
import moni.anyou.com.view.utils.KJHttpBuild;
import moni.anyou.com.view.view.my.RouteTeamActivity;


/**位置发送helper*/
public class LocationSendHelper {

    public static StartLocationBean lastStartLocationBean;

    public static String doubleFormat(double d) {
        double value = new BigDecimal(d).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        return String.valueOf(value);
    }

    public static String doubleFormat(double d,int num) {
        double value = new BigDecimal(d).setScale(num, BigDecimal.ROUND_HALF_UP).doubleValue();
        return String.valueOf(value);
    }

    /**返回路线距离*/
    public static String[] getHaveGone(AMapLocation location, InitTripDataBean tripData) {



        try {
            List<InitTripDataBean.Data.RoutePointList> routePoints = tripData.list.get(0).routePointList;
            //获得路线上最短距离
            int minPoringindex=0;
            double sumDis=0;
            double way=0;
            InitTripDataBean.Data.RoutePointList lastPoint = null;
            double minimum=0;

            InitTripDataBean.Data.RoutePointList minPoint=null;
            System.out.println("routePoints========================"+routePoints.size());
            System.out.println("routePoints latitude========================"+routePoints.get(0).latitude);
            for(int i=0,j=routePoints.size();i<j;i++){
                InitTripDataBean.Data.RoutePointList point = routePoints.get(i);
                double dis = 0;

                    dis = getDistance(location.getLatitude(), location.getLongitude(), Double.valueOf(point.latitude), Double.valueOf(point.longitude));



                Log.d("way","i-->"+i);
                if(lastPoint!=null)
                {
                    sumDis+=between(lastPoint,point);
                    Log.d("way","sumDis-->"+sumDis);
                }

                if(i==0){
                    minimum=dis;
                }else
                {
                    if(minimum<dis)
                    {
                        minPoint=point;
                        minPoringindex=i;
                        way=sumDis;
                        Log.d("way","way-->"+way);
                    }else{

                    }
                }

                lastPoint=point;
            }
            Log.d("way","sum=======================>");
            Log.d("way","minimum-->"+minimum);
            Log.d("way","sumDis-->"+(sumDis));
            Log.d("way","way-->"+(way));
            Log.d("way","sumDis-way-->"+(sumDis-way));
//            //最近的一个点
//            routePoints.get(minPoringindex);



            double beway= 0;
            try{
                beway = getDistance(location.getLatitude(), location.getLongitude(),Double.valueOf(minPoint.latitude), Double.valueOf(minPoint.longitude));
            }
            catch(Exception ex){

            }
            return new String[]{doubleFormat((way+beway)/1000f,3)+"km"
                    ,doubleFormat(((sumDis-way)+beway)/1000f,3)+"km"};


        } catch (Exception e) {
            e.printStackTrace();
        }

        return new String[]{"",""};
    }

    public static double between(InitTripDataBean.Data.RoutePointList lastPoint, InitTripDataBean.Data.RoutePointList point) {
       return (getDistance(Double.valueOf(lastPoint.latitude),
                Double.valueOf(lastPoint.longitude),
                Double.valueOf(point.latitude),
                Double.valueOf(point.longitude)
       ));
    }

    private static double EARTH_RADIUS = 6378.137;

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }


    /**
     * 通过经纬度获取距离(单位：米)
     *
     * @param lat1
     * @param lng1
     * @param lat2
     * @param lng2
     * @return 距离
     */
    public static double getDistance(double lat1, double lng1, double lat2,
                                     double lng2) {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(radLat1) * Math.cos(radLat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000d) / 10000d;
        s = s * 1000;
        return s;
    }



    /**
     * 心跳接口
     * {
     * "cmd": "1",
     * "uid": "1000162",
     * "lastupatetime": "13640405402",
     * "token": "404911573436861",
     * "version": "1",
     * "location": [{
     * "longitude": "110 ",
     * "latitude": "120 ",
     * "altitude": "120 ",
     * "positioningerror": "120 ",
     * "walkeddistance": "120 ",
     * "remaindistance": "120 ",
     * "speed": "0"
     * }]
     * }
     * <p>
     * 发送参数
     * cmd  接口关键字
     * uid  用户ID
     * password 密码
     * lastUpateTime 上次更新时间
     * token
     * version
     * location 定位信息，只有在一个行程已经开始以后才发送，默认为[]
     * longitude 经度
     * latitude  纬度
     * altitude 高度
     * positioningerror 偏离距离（米）
     * walkeddistance 已走距离
     * remaindistance 剩余距离
     * speed 速度
     */



    static class Location {
        String longitude;
        String latitude;
        String altitude;
        String positioningerror;
        String walkeddistance;
        String remaindistance;
        String speed;
        String uid;
        String teamid;
        String icon;
    }
    static class HttpInfo {
        String cmd;
        String uid;
        String lastUpateTime;
        String token;
        String version;
        String teamid;
        List<Location> location;
    }



    public static void sendLocation(final RouteTeamActivity routeTeamActivity, AMapLocation aMaplocation, String teamID, String icon, String haveWay, String notWay, String speed) {

        HttpInfo httpInfo = new HttpInfo();
        httpInfo.cmd = "1";
        httpInfo.uid = SysConfig.uid;
        httpInfo.token = SysConfig.token;
        httpInfo.version = "1";
        httpInfo.lastUpateTime  = String.valueOf(System.currentTimeMillis());
        httpInfo.location = new ArrayList<Location>();
        httpInfo.teamid=teamID;

        Location loc = new Location();
        loc.longitude = String.valueOf(aMaplocation.getLongitude());
        loc.altitude = String.valueOf(aMaplocation.getAltitude());
        loc.latitude = String.valueOf(aMaplocation.getLatitude());
//            positioningerror
        loc.positioningerror = String.valueOf(aMaplocation.getAccuracy());
//            walkeddistance
        loc.walkeddistance = haveWay;
//            remaindistance
        loc.remaindistance = notWay;
        loc.speed = speed;
        loc.uid = SysConfig.uid;
        loc.teamid = teamID;
        loc.icon = icon;
        httpInfo.location.add(loc);





        new KJHttpBuild().setRequestBean(httpInfo)
                .build(new KJHttpBuild.Listen<StartLocationBean>() {

                    @Override
                    public void onSuccessData(String data, StartLocationBean jsonObj) {
                        lastStartLocationBean=jsonObj;

//                        Toast.makeText(routeTeamActivity,data+"->"+LocationSendHelper.lastStartLocationBean,Toast.LENGTH_LONG).show();

                        for(StartLocationBean.RecordList bean:jsonObj.recordList)
                        {
                            String imgUrl=SysConfig.PicUrl+bean.icon;
                            ImageLoader loader = ImageLoader.getInstance();
                            loader.loadImage(imgUrl,null);

                            DisplayImageOptions options = new DisplayImageOptions.Builder()
                                    .cacheInMemory(true)//让图片进行内存缓存
                                    .cacheOnDisk(true)//让图片进行sdcard缓存
                                    .build();
                            Log.d("load",imgUrl);
                            ImageLoader.getInstance().loadImage(imgUrl,options,null);

                        }
                        routeTeamActivity.showHeadIcon(false);
                    }

                    @Override
                    public void onFailure(Throwable t, int errorNo, String strMsg) {

//                        Toast.makeText(routeTeamActivity,"error->"+t.toString()+" "+strMsg,Toast.LENGTH_LONG).show();
                    }
                });


    }

//    {
//        "cmd": "1",
//            "result": "1",
//            "time": "1546825316189",
//            "retmsg": "0|0|0",
//            "filename": "",
//            "apkname": "qianmo.apk",
//            "compIDList": "[]",
//            "recordList": [{
//        "uid": "294",
//                "icon": "route\/20181206170604_940.jpg",
//                "remaindistance": "29.41",
//                "teamid": "5",
//                "speed": "0.0",
//                "altitude": "0.0",
//                "positioningerror": "550.0",
//                "longitude": "121.455387",
//                "latitude": "31.212217",
//                "walkeddistance": "0.0"
//    }, {
//        "uid": "292",
//                "icon": "icon\/icon.png",
//                "remaindistance": 27861.659616606346,
//                "teamid": "5",
//                "speed": -1,
//                "altitude": 0,
//                "positioningerror": 5,
//                "longitude": 118.58337076822917,
//                "latitude": 30.052875162760415,
//                "walkeddistance": 0
//    }]
//    }
}
